
'''
async web application.
'''

import logging; logging.basicConfig(level=logging.INFO)

import asyncio, os, json, time
from datetime import datetime
import orm
from pmodel import User

from aiohttp import web

def index(request):
    return web.Response(body=b'<h1>Awesome</h1>',content_type="text/html")
async def add(request):
    u = User(name='Test4', email='test4@qq.com', passwd='1234567890', image='about:blank')
    await u.save()
    return web.Response(body=b'<h1>add ok </h1>',content_type="text/html")
async def find(request):
    us=[]
    us = await User.findAll()
    s="<h1>find all ok </h1>"
    # for x in us:
    s+=str(us)
    return web.Response(body=str.encode(s),content_type="text/html")
async def init(loop):
    await orm.create_pool(loop=loop, user='root', password='root', db='awesome')
    app = web.Application()
    app.router.add_route('GET', '/', index)
    app.router.add_route('GET', '/add', add)
    app.router.add_route('GET', '/find', find)
    srv = await loop.create_server(app.make_handler(), '127.0.0.1', 9000)
    logging.info('server started at http://127.0.0.1:9000...')
    return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()